<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Role_model extends MY_Model
{
	public $_table = 'roles';

	public function __construct()
	{
		parent::__construct();

		// Other stuff
		$this->_prefix = $this->config->item('table_prefix');
		$this->_table = $this->_prefix.$this->config->item('roles_table');
	}

	public function get_all()
	{
		$this->db->select("$this->_table.*, parent.name as parent_name");
		$this->db->join("$this->_table AS parent", "$this->_table.parent_id = parent.id", "left");
		$this->db->order_by("$this->_table.id ASC");
		
		return $this->db->get($this->_table);
	}
	
	public function find_all($condition = '', $order_by = '', $limit = 1, $offset = 0)
	{
		$this->db->select("$this->_table.*, parent.name as parent_name");
		$this->db->join("$this->_table AS parent", "$this->_table.parent_id = parent.id", "left");

		if($condition)
		{
			$this->db->where($condition);
		}

		if($order_by)
		{
			$this->db->order_by($order_by);
		}

		if ($offset >= 0 AND $limit > 0)
		{
			$this->db->limit($limit, $offset);
		}

		return $this->db->get($this->_table);
	}

	public function get_role_by_id($role_id)
	{
		$this->db->where('id', $role_id);
		return $this->db->get($this->_table);
	}

	public function create_role($name, $parent_id = 0)
	{
		$data = array(
			'name' => $name,
			'parent_id' => $parent_id
		);

		$this->db->insert($this->_table, $data);
	}

	public function delete_role($role_id)
	{
		$this->db->where('id', $role_id);
		$this->db->delete($this->_table);
	}
}
